﻿//-----------------------------------------------------------------------
// <copyright file="ContactManagerNhSessionFactoryCfg.cs" company="OverrideThis">
//     Copyright (c) 2010 OverrideThis.com
// </copyright>
//-----------------------------------------------------------------------
namespace OverrideThis.ContactManager.Infrastructure.Repository.Cfg
{
    using System;
    using System.Reflection;
    using FluentNHibernate.Automapping;
    using FluentNHibernate.Cfg;
    using FluentNHibernate.Cfg.Db;
    using NHibernate.Cfg;
    using OverrideThis.ContactManager.Domain;
    using OverrideThis.Core.Domain;
    using OverrideThis.Core.Infrastucture.Repository.Impl;

    public class ContactManagerNhSessionFactoryCfg : INhSessionFactoryCfg
    {
        private readonly string connKey;

        public ContactManagerNhSessionFactoryCfg(string connKey)
        {
            this.connKey = connKey;
        }

        #region Implementation of INhSessionFactoryCfg

        public Action<MappingConfiguration> Mapping()
        {
            return m => m.AutoMappings.Add(
                    AutoMap.Assemblies(new CustomAutomappingConfiguration(), Assembly.GetAssembly(typeof(Person)))
                        .IncludeBase<Contact>()
                        .Override<Person>(map => map.HasMany(prop => prop.Contacts).Cascade.AllDeleteOrphan())
                );
        }

        public IPersistenceConfigurer Provider()
        {
            return MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey(this.connKey));
        }

        public void ExposeConfiguration(Configuration mapping)
        {
            // Do Nothing.
        }

        #endregion

        #region CustomAutomappingConfiguration

        public class CustomAutomappingConfiguration : DefaultAutomappingConfiguration
        {
            public override bool ShouldMap(FluentNHibernate.Member member)
            {
                return member.CanWrite && member.IsProperty && base.ShouldMap(member);
            }

            public override bool ShouldMap(Type type)
            {
                return typeof(IEntity).IsAssignableFrom(type);
            }
        }

        #endregion
    }

}
